layui.use('laydate', function(){
  var laydate = layui.laydate;
  laydate.render({
    elem:'#clDate',
    done: function(value, date, endDate){
	   $('#clDate').blur();
	}
  });
});
var qklStatus;//当前的审核状态
$('form').validate({
    rules: {
       
    },
    messages: {
        
    },
    onFocus: function () {
        this.parent().addClass('active');
        return false;
    },

    onBlur: function () {
        var $parent = this.parent();
        var _status = parseInt(this.attr('data-status'));
        $parent.removeClass('active');
        if (!_status) {
            $parent.addClass('error');
        };
        if(_status == 1 && qklStatus==0 || qklStatus==-1){
        	  save();
        };
        //console.log(qklStatus);
        return false;
    }
});
//序列化表单
$.fn.serializeObject = function() {
  var o = {};
  var a = this.serializeArray();
  $.each(a, function() {
   if (o[this.name]) {
    if (!o[this.name].push) {
     o[this.name] = [ o[this.name] ];
    }
    o[this.name].push(this.value || '');
   } else {
    //console.log(this,$("[name="+this.name+"]").attr('type'))
    if($("[name="+this.name+"]").attr('type') === "checkbox"){
     o[this.name] = [ this.value ];
    }else{
     o[this.name] = this.value || '';
    }
   }
  });
  return o;
};
//文本域字数监听
function callText(a){
	var textLength = $('textarea[name='+a+']').val().length;
	/*if(textLength>150){
		textLength=150
	}*/
	$('textarea[name='+a+']').next().find('.textNum').text(textLength);
}
//判断是否为其他
$('select[name="applicationScenarios"]').change(function(){
	if($(this).val() == '其他'){
		$('#qtBox').append('<input type="text" id="qita" placeholder="请输入"  class="required" data-valid="isNonEmpty" data-error="*请输入"/>');
	}else{
		$('#qita').remove();
		$('#qtBox .valid_message').remove();
		$('#qtBox').removeClass('error');
	}
});
//var qklStatus;//当前的审核状态
function subMit(){
	if($('form').validate('submitValidate')){
		var reData = $("#inforForm").serializeObject();
		if($('select[name="applicationScenarios"]').val() == '其他'){
			reData.applicationScenarios = $('#qita').val();
		}
		reData.foundationDate = $('#clDate').val()+' 00:00:00';//接口里面需要时分秒
		//console.log(reData);
		var jsonStringify = JSON.stringify(reData);
		//console.log(reData);
		/*console.log(getCookie("token"))*/
		if(qklStatus == 1 || qklStatus == -1 || qklStatus == 0){
				$.ajax({
				type: "POST",
				url: qklUrl+"/enterpriseBolckchainDirectory/commit",
				contentType: "application/json", //必须有  
				// dataType: "json", //表示返回值类型，不必须
				data: jsonStringify,
				xhrFields: {
					withCredentials: true // 这里设置了withCredentials
				},
				success: function (result) {
					/*console.log(result);*/
					//isTimer(0);//点击提交后
					if(result.status == 1){
						$(".popWrap").show();
					}else{
						alert(result.message);
					}
				}
			});
		}
		
	}else{
		var oPosition = $('.error:first').offset().top;
		$('html,body').animate({
  		scrollTop:oPosition
  	},10)
	}
}
$.ajax({
	type:"get",
	url: qklUrl+"/enterpriseBolckchainDirectory/detail",
	contentType: "application/json", //必须有  
	// dataType: "json", //表示返回值类型，不必须
	data:{},
	xhrFields: {
		withCredentials: true // 这里设置了withCredentials
	},
	success: function (result) {
		//console.log(result);
		qklStatus = result.data.status;
		if(result.data.status == 1){
			$(".qkl_status").append('审核状态：<span>待审核</span>');
			/*$('.btn-wrap a').eq(1).css('background-color','#ccc');
			$('.btn-wrap a').eq(1).removeAttr('onclick');*/
      //isTimer(0);//取消自动保存 
      $('.btn-wrap a').eq(1).css('background-color:#ccc');
		}else if(result.data.status == -1){
			$(".qkl_status").append('审核状态：<span>待提交</span>');
			//isTimer(1);
		}else if(result.data.status == 0){
			$(".qkl_status").append('审核状态：<span>待提交</span>');
			//isTimer(1);
		}else if(result.data.status == 2){
			$(".qkl_status").append('审核状态：<span>通过</span>');
			$('.btn-wrap a').eq(1).css('background-color','#ccc');
			$('.btn-wrap a').eq(1).removeAttr('onclick');
			readForm();//只读
			//isTimer(0);//取消自动保存
		}else if(result.data.status == 3){
			$(".qkl_status").append('审核状态：<span>未通过</span>');
			$('.btn-wrap a').eq(1).css('background-color','#ccc');
			$('.btn-wrap a').eq(1).removeAttr('onclick');
			readForm();//只读
			//isTimer(0);//开启自动保存 		
		}
		initForm(result.data);
		$('textarea').each(function(el,value){
			$(this).next().find('.textNum').text($(this).val().length);
		})
	}
});
//initForm(dataJson);
//初始化表单
function initForm(jsonStr){
	var obj = eval(jsonStr);
	//console.log(obj);
	var key,value,tagName,type,arr;
	for(x in obj){
		key = x;
		value = obj[x];
		$("[name='"+key+"'],[name='"+key+"[]']").each(function(){
			tagName = $(this)[0].tagName;
			type = $(this).attr('type');
			if(tagName=='INPUT'){
				if(type=='radio'){
					$(this).attr('checked',$(this).val()==value);
				}else if(type=='checkbox'){
					//arr = value.split(',');
					arr = value;
					for(var i =0;i<arr.length;i++){
						if($(this).val()==arr[i]){
							$(this).attr('checked',true);
							break;
						}
					}
				}else if(type=='text'){
					$(this).val(value);
				}
			}else if(tagName=='SELECT'){
				var that = $(this);
				if(key == "applicationScenarios"){
					var flag = false;
					$.each($("#qtBox select option"), function(i,item) {
						//console.log(item.value);
						if(item.value == value){
							     flag = true;
		               that.val(value);
		               return false;
		        }
					});
					if(!flag){
						that.val('其他');
		        $('#qtBox').append('<input type="text" value="'+value+'" id="qita" placeholder="请输入"  class="required" data-valid="isNonEmpty" data-error="*请输入"/>');
		          	  
					}
				}else{
					$(this).val(value);
				}
			}else if(tagName=='TEXTAREA'){
				$(this).val(value);
			}
			
		});
	}
}
/*自动保存操作*/
function save(){
	var reData = $("#inforForm").serializeObject();
	if($('select[name="applicationScenarios"]').val() == '其他'){
		reData.applicationScenarios = $('#qita').val();
	}
	if($('#clDate').val()){
		reData.foundationDate = $('#clDate').val()+' 00:00:00';//接口里面需要时分秒
	}
	if($('input:radio[name="highTechEnterprises"]:checked').val()==undefined){
		reData.highTechEnterprises = "";
	}
	/*if($('input[name="enterpriseType"]').val()!=undefined){
		reData.enterpriseType = "";
	}*/
	console.log(reData);
	var jsonStringify = JSON.stringify(reData);
	$.ajax({
		type: "POST",
		url: qklUrl+"/enterpriseBolckchainDirectory/save",
		contentType: "application/json", //必须有  
		// dataType: "json", //表示返回值类型，不必须
		data: jsonStringify,
		xhrFields: {
			withCredentials: true // 这里设置了withCredentials
		},
		success: function (result) {
			/*console.log(result);*/
			if(result.status!=1){
				//isTimer(0);
			}
		},
		error:function(){
			//isTimer(0);
		}
	});
}
function isTimer(flag){
	/*var timer;
    //每隔7s执行一次保存逻辑
    if(flag == 1){
    	timer = setInterval(function(){
            save()
        },7000)
    }else{
    	clearInterval(timer);
    }*/
}

$('#popClose').click(function(){//关闭弹窗
	$(".popWrap").hide();
	$('body').css("height","");
	$('body').css("overflow","scroll");
	window.location.reload();
});
function closewin(){
	$(".popWrap").hide();
	$('body').css("height","");
	$('body').css("overflow","scroll");
	window.location.reload();
}
/*点击logo跳转*/
function indexLink(){
	window.location.href=indexUrl;
}
/*设置表单元素为只读方法*/
//readForm();
function readForm(){
	$('#inforForm').find('input,textarea,select').attr('disabled',true); 
}
/*关闭当前窗口*/
function closewin(){
    window.opener=null;
    window.open('','_self');
	  window.close();
}